import { Product } from 'product-model.js';
import { Cart } from '../cart/cart-model.js';
import { Evaluate } from '../evaluate/evaluate-model.js';
import { Order } from '../order/order-model.js';
var WxParse = require('../../utils/wxParse/wxParse.js');
import { Collection } from '../collection/collection-model.js';
var collection = new Collection();
var product = new Product(); 
var cart = new Cart();
var evaluate = new Evaluate();
var order = new Order();
import { Home } from '../home/home-model.js';
var home = new Home();
var selectLabel;
var interval;
Page({
  data: {
      hiddenAttrBox:true,
      productCounts: 1,
      allselect:0 ,//sku全选中状态，1表示全选中 
      showpost:false,
      haopinglv : null,
      comment_item: [],
      comment_count:0,
  },
  onLoad: function (option) {
    var user = wx.getStorageSync('userInfo');
    this.setData({user});
    var share_mid = wx.getStorageSync('uid');
    var id = option.id;
    //二维码进入
    if (option.scene) {
      var scene = decodeURIComponent(option.scene);
      var arr = scene.split("&");
      id = arr[0];
      if (arr[1]) {
        this.data.pid = arr[1];
        wx.setStorageSync('share_mid', arr[1]);
      }
    }
    this.data.id = id;
    if(option.skuid){
      var skuid = option.skuid;
      this.data.skuid = skuid
      //分享路径
      this.data.path = 'pages/product/product?id=' + id + '&skuid=' + skuid + '&share_mid=' + share_mid
    }else{
      this.data.path = 'pages/product/product?id=' + id + '&share_mid=' + share_mid
    }
    this._loadData();
    var config = wx.getStorageSync('config');
    if (!config) {
      this.getConfig();
    }
  },
  getConfig: function () {
    var that = this;
    //获得小程序名称
    home.getXcxName((data) => {
      var config = data.items;
      wx.setStorageSync('config', config);
    });

  },
  /*加载所有数据*/
  _loadData: function (callback) {
    var that = this;
    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options; //如果要获取url中所带的参数可以查看options
    var params = {};

    if (options.share_mid){
      params = {
        'product_id': this.data.id,
        'share_mid': options.share_mid
      }
    }else{
      params = {
        'product_id': this.data.id,
      }
    }
    product.getDetailInfo(params, (data) => {
      product.setAttrValuesStock(data);
      //判断是否只有一个规格属性值则表现为选中状态
      var attr_len = data.attributes && data.attributes && data.attributes.length;
      var selectLabel = '已选';
      var selectedAttributes = [];
      for (var i = 0; i < attr_len; i++) {
        var attr_child_len = data.attributes[i].child.length
        if (attr_child_len == 1) {
          data.attributes[i].child[0].is_select = 1;
          selectLabel += ' ' + data.attributes[i].child[0].value_str;
          selectedAttributes.push(data.attributes[i].child[0].value_id);
          this.setData({
            selectLabel: selectLabel,
          })
        }

      }
      //如果有正在进行的营销活动则选中sku
      if(data.product.status==1&&data.product.prom_status==1){
        
        //若已选择完整的属性，判断由这些属性组成的SKU是否正在参加营销活动，如果在参加，显示营销价格
        var myLength = selectedAttributes.length;
        if (myLength == attr_len)
        {
          var product_id = data.product.product_id;
          var str = product_id;
          for (var i = 0; i < myLength; i++) {
            str += '_' + selectedAttributes[i];
          }
          this.data.skuid = str;
        }
        
        var skus = data.skus;
        var index;
        for (var i = 0; i < skus.length; i++){
          if(skus[i].prom){
            if (this.data.skuid == skus[i].prom.sku_id){
              this.data.end_time = skus[i].prom.end_time;
              if (skus[i].prom.proming_status == 1){
                this.data.prom_id = data.product.prom_id;
                this.data.prom_type = data.product.prom_type;
              }
              this.counTtime(this.data.end_time);
              var skus_val = JSON.parse(data.skus[i].sku_values);
              this.data.current_sku_prom = skus[i].prom;
              var selectLabel = '已选'
              for (let key in skus_val) {
                selectLabel += ' ' + skus_val[key];
              }
              
              this.setData({
                selectLabel: selectLabel,
                allselect: 1,
                'skus': data.skus[i],  
              })
              var skus_id = this.data.skuid;
              for (var k = 0; k < attr_len; k++) {
                var len = data.attributes[k].child.length;
                for (var m = 0; m < len; m++) {
                  if (skus_id.indexOf(data.attributes[k].child[m].value_id) != -1) {
                    data.attributes[k].child[m].is_select = 1;
                  }
                }
              }
              break;
            }
          }
        }
      }else{
        this.data.prom_type = 0;
        this.data.prom_id = 0;
      }
      var unselectLabel="";
      for (var i = 0; i < data.attributes.length;i++){
        unselectLabel += data.attributes[i].attribute_name+' ';
      }
      
      that.setData({
        productDetail: data,
        unselectLabel: unselectLabel
      });
     
      if (data.product.content){
        WxParse.wxParse('content', 'html', data.product.content, that, 0)
      }
      
      callback && callback();
    });
    cart.getCartData((data) => {
      if (data.items){
        var countsInfo = cart.getCartTotalCounts(false, data.items);
        that.setData({
          cartData: data,
          cartTotalCounts: countsInfo.counts1
        });
      }  
    });
    var comment_param = {'goods_id': this.data.id,'num':1}
    evaluate.getEvalLists(comment_param, 1, (data) => {
      //好评率转化
      var haopinglv = data.comment_count.haopinglv * 100;
      that.setData({
        comment_item: data.items,
        haopinglv,
        comment_count: data.comment_count.all_count
      })
    })
  },

  //秒杀倒计时
  counTtime: function (endtime) {
    var nowtime = Date.parse(new Date()) / 1000
    var second = endtime - nowtime;
    interval = setInterval(function () {

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;
      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      second--;

    }.bind(this), 1000);

  },


  //商品属性弹出框
  showattrbox: function (e) {
    /*是否需要授权 */
    var config = wx.getStorageSync('config');
    var auth = '';
    if (config[23]) {
      auth = config[23].value;
    }
    if (auth == 1 && this.data.user.username == '小程序用户') {
      wx.setStorageSync('redirect-url', '/pages/product/product?id=' + this.data.id + '&pid=' + this.data.pid);
      wx.navigateTo({
        url: '../home/login',
      })
      return false;
    }
    /* */
    this.setData({
      'hiddenAttrBox': false, 
    });
  },
  // 跳转到评价列表
  gotoAllEval:function(event){
    var id = product.getDataSet(event,'id')
    wx.navigateTo({
      url: '../evaluate/allList?id='+id,
    })
  },
  //跳转页面
  toCartTap: function () {
    wx.switchTab({
      url: '../cart/cart',
    })
  },

  toHomeTap: function () {
    wx.switchTab({
      url: '../home/home',
    })
  },

  // 收藏
  toCollectionTap:function(){
    var isFavorite = this.data.productDetail.isFavorite
    if (isFavorite == 0){
      collection.getCollectionAdd(this.data.id,(res)=>{
        var status = res.status;
        if(status == 1){
          this.setData({
            'productDetail.isFavorite': 1
          })
          wx.showToast({
            title: '收藏成功~',
            icon: 'none',
            duration: 2000
          })

        }
      })

    }
    if (isFavorite == 1){
      collection.getCollectionDel(this.data.id, (res) => {
        var status = res.status;
        if (status == 1) {
          this.setData({
            'productDetail.isFavorite': 0
          })
          wx.showToast({
            title: '收藏取消~',
            icon: 'none',
            duration: 2000
          })
        }
      })

    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage:function () {
    var productData = this.data.productDetail.product;
    var path = this.data.path;
    return {
      title: productData.name,
      path:path
    } 
  },
  //点击分享按钮
  toShare:function(){
    this.showShare();
  },
  /**
   * 展示分享弹框
   */
  showShare: function () {
    this.setData({
      showShare : true
    })
  },
  setnum:function(){

  },
    
  /**
   * 隐藏分享弹框
   */
  hiddenShare: function () {
    this.setData({
      showShare: false
    })
  },
  //调用子组件的方法
  getSharePoster: function () {
    this.setData({
      showpost : true
    })
    this.hiddenShare();
    this.selectComponent('#productPoster').getDiy(this.data.hasPost)
  },
  myEventListener: function (e) {
    this.setData({
      showpost: false,
      hasPost: e.detail.status
    })
  },
  //页面卸载
  onUnload:function(){
    //销毁倒计时
    clearInterval(interval);
  }
})